package com.ourteam.system.api;

import com.ourteam.frame.web.AbstractTreeNodeBuilder;
import com.ourteam.system.dao.SysModuleDAOQueryBean;
import com.ourteam.system.domain.ApplicationDomain;
import com.ourteam.system.domain.SystemModule;
import com.ourteam.system.service.ISystemApplicationService;
import com.ourteam.system.service.SystemApplicationServiceFactory;

public class SystemDomainModuleNodeBuilder extends AbstractTreeNodeBuilder<ApplicationDomain, SystemModule> {

	private final static ISystemApplicationService applicationService = SystemApplicationServiceFactory
			.getSystemApplicationService();

	@Override
	public SystemModule[] getTreeNodeObjects(ApplicationDomain parentObject) throws Exception {
		return applicationService.getSystemModules(parentObject.getId(), 0);
	}

	@Override
	public Object getNodeId(SystemModule childObject) {
		return childObject.getId();
	}

	public boolean isLeaf(SystemModule childObject) throws Exception {

		SysModuleDAOQueryBean queryBean = new SysModuleDAOQueryBean();

		SysModuleDAOQueryBean.Criteria criteria = queryBean.createCriteria();

		criteria.andDomainIdEqualTo(childObject.getDomainId()).andParentModuleIdEqualTo(childObject.getId());

		return applicationService.querySystemModules(queryBean).length == 0
				&& applicationService.getSystemActions(childObject.getId()).length == 0;
	}

	@Override
	public String getNodeDefineId(SystemModule childObject) throws Exception {
		return "sysModule";
	}

	@Override
	public ApplicationDomain converToParentObject(Object parent) throws Exception {
		return applicationService.getApplicationDomainById(Long.parseLong(parent.toString()));
	}

	@Override
	public int getChildCount(SystemModule childObject) throws Exception {

		SysModuleDAOQueryBean queryBean = new SysModuleDAOQueryBean();

		SysModuleDAOQueryBean.Criteria criteria = queryBean.createCriteria();

		criteria.andDomainIdEqualTo(childObject.getDomainId()).andParentModuleIdEqualTo(childObject.getId());

		return applicationService.querySystemModules(queryBean).length
				+ applicationService.getSystemActions(childObject.getId()).length;
	}

}
